<?php


namespace app\controller;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use think\facade\Db;
class Excel
{
    public function upload(){
        $file = request()->file('file');
        $savename = [];
        try {
            // 验证文件大小，名称等是否正确10M
            validate(['file'=>['filesize'=>10485760, 'fileExt'=>'xls,xlsx']])->check(['file'=>$file]);
            // 将文件保存到本地
            $savename= \think\facade\Filesystem::disk('public')->putFile( 'topic', $file);
            // 截取后缀
            $fileExtendName = substr(strrchr($savename, '.'), 1);
            // 有Xls和Xlsx格式两种
            if ($fileExtendName == 'xlsx') {
                $reader = IOFactory::createReader('Xlsx');
            } else {
                $reader = IOFactory::createReader('Xls');
            }

            $reader->setReadDataOnly(TRUE);//忽略任何格式的信息
            $spreadsheet = $reader->load(public_path() . 'storage/' . $savename); //载入excel表格
            $worksheet = $spreadsheet->getActiveSheet();//获取数据
            $sheet = $spreadsheet->getSheet(0);   //excel中的第一张sheet
            $highestRow = $worksheet->getHighestRow(); // 总行数
            $highestColumn = $worksheet->getHighestColumn(); // 总列数
            Coordinate::columnIndexFromString($highestColumn);
            $lines = $highestRow - 1;
            if ($lines <= 0) {
                return ['status'=>500,'msg'=>'数据不能为空！'];
                exit();
            }
            // 直接取出excle中的数据
            $data = $spreadsheet->getActiveSheet()->toArray();
            // 删除第一个元素（表头）
            array_shift($data);
            $city = [];
            foreach($data as $k=>$v) {
                $city[$k]['name'] = $v[0];
                $city[$k]['phone'] = $v[1];
            }
            Db::table("test")->insertAll($city);
            try {
                return json(['status'=>200,'msg'=>'数据导入成功！']);
            } catch (Exception $e) {
                return ['status'=>500,'msg'=>$e->getMessage()];
            }


        } catch (ValidateException $e) {
            return json(['status'=>500,'data'=>$e->getMessage()]);
        }

    }
    public function send(){

    }
}